const db = require('../db/index')
const {nodeMail} = require('../utils/nodemailer')
// 导入 bcrypt  --------- 对密码进行加密处理
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../utils/config')


// 发送邮箱验证码
exports.sendCode = (req, res) => {
    const userEmail = req.body.userEmail
    console.log(userEmail)
    const email_code = String(Math.floor(Math.random() * 1000000)).padEnd(6, '0') //生成6位随机验证码
    // res.setHeader('Content-Type','text/html;charset=utf-8')
    //发送邮件
    const mail = {
        from: `"立修宝"<625118310@qq.com>`,// 发件人
        subject: '验证码',//邮箱主题
        to: userEmail,//收件人，这里由post请求传递过来
         // 邮件内容，用html格式编写
        html: `
            <p>您好！</p>
            <p>您的验证码是：<strong style="color:orangered;">${email_code}</strong></p>
            <p>如果不是您本人操作，请无视此邮件</p>
        ` 
    }
    nodeMail.sendMail(mail, (err, info) => {
        if (err) {
            res.cc("验证码发送失败，请稍后重试")
        } else {
            console.log('success')
            res.send({
                status: 0,
                message:'验证码发送成功',
                data:{
                    email_code
                }
            })
        }
    })
}

// 注册
exports.register = (req, res) => {
    const data = req.body
    // console.log(data)
    const selectSql = 'select * from user where userEmail=?'
    db.query(selectSql, data.userEmail, (err, resutles) => {
        if(err) return res.cc(err)
        if(resutles.length === 1) return res.cc('用户已经存在')
        // 对密码进行加密
        data.password = bcrypt.hashSync(data.password, 10)
        // console.log(data.password)
        const insertSql = 'insert into user set ?'
        db.query(insertSql, data , (err, resutles) => {
            if(err) return res.cc(err)
            if(resutles.affectedRows !== 1) return res.cc('注册失败')
            res.cc('注册成功', 0)
        })
    })
}

// 登录
exports.login = (req, res) => {
    const data = req.body
    let selectSql = ''
    if(data.role === '1'){
        selectSql = 'select * from user where userEmail=?'
    }else{
        selectSql = 'select * from maintainer where maintainer_email=? and status=?'
    }
    
    db.query(selectSql, [data.userEmail,'0'], (err, results) => {
        // console.log(resutles[0])
        if(err) return res.cc(err)
        if(results.length  !== 1) return res.cc('登录失败！用户不存在')
        // TODO1：判断密码是否正确----bcrypt.compareSync(用户提交的密码, 数据库的密码)
        const compareResults = bcrypt.compareSync(data.password, results[0].password)
        if(!compareResults) return res.cc('登录失败，密码错误')

        // TODO2：登录成功，生成token返回给客户端
        const userInfo = { ...results[0], password : '', avatar : ''}
        // 对用户的信息进行加密，生成token
        const token = jwt.sign(userInfo, config.jwtSecreKey, { expiresIn: config.expiresIn })
        res.send({
            status : 0,
            message : '登录成功',
            data:{
                userId: results[0].id,
                token
            }
        })
    })
}

// 维修员注册申请
exports.maintainerreg = (req, res) => {
    const data = req.body
    data.status = '1'
    const sql = 'select * from maintainer where maintainer_email=?'
    db.query(sql,  data.maintainer_email, (err, resutles) => {
        if(err) return res.cc(err)
        if(resutles.length === 1) return res.cc('用户已存在')
        // 对密码进行加密
        data.password = bcrypt.hashSync(data.password, 10)
        const insertSql = 'insert into maintainer set ?'
        db.query(insertSql, data , (err, resutles) => {
            if(err) return res.cc(err)
            if(resutles.affectedRows !== 1) return res.cc('申请失败')
            res.cc('申请成功', 0)
        })
    })
}

// 管理员登录
exports.adminlogin = (req, res) => {
    const data = req.body
    const selectSql = 'select * from admin where adminName=?'
    db.query(selectSql, data.adminName, (err, resutles) => {
        if(err) return res.cc(err)
        if(resutles.length  !== 1) return res.cc('登录失败！用户不存在')
        // TODO1：判断密码是否正确----bcrypt.compareSync(   )
        const compareResults = bcrypt.compareSync(data.password, resutles[0].password)
        if(!compareResults) return res.cc('登录失败，密码错误')
        // TODO2：登录成功，生成token返回给客户端
        const userInfo = { ...resutles[0], password : ''}
        // 对用户的信息进行加密，生成token
        const token = jwt.sign(userInfo, config.jwtSecreKey, { expiresIn: config.expiresIn })
        res.send({
            status : 0,
            message : '登录成功',
            data:{
                adminId: resutles[0].id,
                token
            }
        })
    })
}

// 添加管理员
/* exports.addadmin = (req, res) => {
    const data = req.body
    // console.log(data)
    const selectSql = 'select * from admin where adminName=?'
    db.query(selectSql, data.adminName, (err, resutles) => {
        if(err) return res.cc(err)
        if(resutles.length === 1) return res.cc('用户已经存在')
        // 对密码进行加密
        data.password = bcrypt.hashSync(data.password, 10)
        // console.log(data.password)
        const insertSql = 'insert into admin set ?'
        db.query(insertSql, data , (err, resutles) => {
            if(err) return res.cc(err)
            if(resutles.affectedRows !== 1) return res.cc('添加失败')
            res.cc('注册成功', 0)
        })
    })
} */

// 查看所有师傅的介绍
exports.getAllMaintainers = (req, res) => {
    const selectSql = 'select * from maintainer where status=?'
    db.query(selectSql, '0', (err, resutles) => {
        if(err) return res.cc(err)
        if(resutles.length === 0) return res.cc('没有师傅')
        resutles.forEach(item => {
            item.password = ''
        })
        res.send({
            status : 0,
            message : '查询成功',
            data:{
                maintainers: resutles
            }
        })
    })
}